<template>
    <div :class="['main', 'pui-theme', store.state.theme === 'dark' && 'pui-theme__dark']">
        <LayoutHeader @sysTypeChange="sysTypeChange" />
        <OptiSystemContent :toolbarList="mainRef.sysToolbarList" v-show="store.state.sysType === 'system'" />
        <OptiPassiveDeviceContent :toolbarList="mainRef.passiveDeviceToolbarList" v-show="store.state.sysType === 'passive_device'" />
        <OptiActiveDeviceContent :toolbarList="mainRef.passiveDeviceToolbarList" v-show="store.state.sysType === 'active_device'" />
        <LayoutFooter />
    </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
    name: 'PhotDesignMain'
})
</script>

<script lang="ts" setup>
import { ipcRenderer } from 'electron'
import { onMounted, onBeforeUnmount, onUnmounted, ref, reactive } from 'vue'
import mainData from './index'
import LayoutHeader from '../LayoutHeader/LayoutHeader.vue'
import LayoutFooter from '../LayoutFooter/LayoutFooter.vue'
import OptiSystemContent from '../../components/phot_system/LayoutContent.vue'
import OptiPassiveDeviceContent from '../../components/phot_passive_device/LayoutContent.vue'
import OptiActiveDeviceContent from '../../components/phot_active_device/LayoutContent.vue'
import { libraryService as library } from '@/services/phot_client/client'
import { graphManager } from '@/services/phot_client/graph'
import { libraryManager } from '@/services/phot_client/library'
import { useStore } from 'vuex'

const isRefreshBlocked = ref(false)
const store = useStore()
const mainRef = reactive(mainData.mainRef)
const sysRef = reactive({
    sysType: "system"
})
const sysTypeChange = (e:any) => {
    sysRef.sysType = e.type
    // store.dispatch('setSysType', e ? 'system' : 'compo')
    // localStorage.setItem('sysType', e ? 'system' : 'compo')
    store.dispatch('setSysType', e.type)
    localStorage.setItem('sysType', e.type)
    store.dispatch('setSysName', e.title)
    localStorage.setItem('sysName', e.title)
}
const getLibraryList = async () => {
    if (store.state.libraryList.length > 0) return
    const res = await libraryManager.getLibraryList()
    store.dispatch('setLibraryList', res.libraryList)
    store.dispatch('setAllLibraryList', res.allList)
}
const listenBeforeUnload = () => {  
    window.addEventListener('beforeunload', async (event) => {
        isRefreshBlocked.value = true; // 标记为正在执行操作，阻止刷新
        try {
            // 执行异步操作
            await graphManager.closeAllOpenedGraph();
            isRefreshBlocked.value = false;
            // 操作完成后，允许刷新
        } catch (error) {
            console.error('异步操作失败:', error);

            // 根据错误情况，你可能想要决定是否允许刷新
            // 例如，如果错误是可以恢复的，你可能想要设置 isRefreshBlocked.value = false
            // 否则，你可能需要处理错误并让用户知道操作失败
        }

        // 设置 event.returnValue 为任意字符串将取消事件的默认行为
        // 在 Electron 中，如果 event.returnValue 未被设置，窗口将关闭或刷新
        // 如果你不想在操作失败时阻止刷新，确保在这里不要设置 event.returnValue
        if (isRefreshBlocked.value) {
            event.returnValue = false; // 在 Electron 中，通常设置为 false 来阻止刷新
        }
    })
}
const removeBeforeUnloadListener = () => {
    window.removeEventListener('beforeunload', listenBeforeUnload)
}
onMounted(async () => {
    listenBeforeUnload()
    if (!store.state.libraryList || store.state.libraryList.length === 0) {
        await getLibraryList()
    }
    if (localStorage.getItem('theme')) {
        let theme = localStorage.getItem('theme')
        store.dispatch('setTheme', theme)
    }
    if (localStorage.getItem('sysType')) {
        let sysType = localStorage.getItem('sysType')
        store.dispatch('setSysType', sysType)
    }
    if (localStorage.getItem('sysName')) {
        let sysName = localStorage.getItem('sysName')
        store.dispatch('setSysName', sysName)
    }
    if (localStorage.getItem('sysType')) {
        let sysType = localStorage.getItem('sysType')
        store.dispatch('setSysType', sysType)
    }
    setTimeout(async () => {
        const defaultSaveRoot = await ipcRenderer.invoke('DefaultRoot')
        store.dispatch('setDefaultSaveRoot', defaultSaveRoot)
        if (!store.state.saveRoot) {
            store.dispatch('setSaveRoot', defaultSaveRoot)
        }
        mainRef.setting = ipcRenderer.sendSync('getStore', '_setting')
        if (!mainRef.setting) {
            mainRef.setting = {
                "locale":"zh-CN",
                "theme":"light",
                "savePath": defaultSaveRoot,
                "server":{
                    "ip":"114.112.124.182",
                    "port":"8000"
                    // "ip":"127.0.0.1",
                    // "port":"9000"
                },
                "backupTime":"15",
                "autoSave":true
            }
            ipcRenderer.send('setStore', '_setting', mainRef.setting)
        }
    }, 500)
})
onUnmounted(() => {
    removeBeforeUnloadListener()
})
</script>
<style lang="scss">
</style>
